package com.lazy.common.dao.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

import com.lazy.common.dao.itf.IBaseDao;
import com.lazy.common.utils.entity.Page;

/**
 * @Auther: lujia
 * @Title: BaseDaoImpl.java
 * @Description: (请用一句话来描述)
 * @Date:2019年12月12日 09:46:17
 * @Version: 1.0
 */
@Repository("baseDao")
public class BaseDaoImpl implements IBaseDao{
	
	@Resource(name = "lazySqlSession")  
    protected SqlSessionTemplate crmSqlSession;  
	
	/**
	* @Title: pageSelect <pre>
	* @Description: 分页查询
	* @param clazz
	* @param p
	* @param attrs
	* @param values
	* @return    参数 <pre>
	* @date:   2019年12月12日 上午10:00:08    <pre>
	* @throws 异常: <pre>
	* @author lujia
	*/
	@Override
	public <T extends Serializable> Page<T> pageSelect(Class<T> clazz, Page<?> p, String[] arrs, Object[] values) {
		Map<String, Object> paraMap = new HashMap<String, Object>(); 
		if(values!=null&&arrs!=null) {
			for(int i=0;i<values.length;i++) {
				paraMap.put(arrs[i], values[i]);
			}
		}
		//1 创建分页对象Page<T>
		Page<T> responsePage=new Page<T>();
	    String statement = getStatement(clazz, "page");
		if(p!=null) {
		//2 请求参数封装成map
			int startNum=p.getStartIndex();
			int pageSize=p.getPageSize();
			int endNum=startNum+pageSize;
			paraMap.put("startNum",startNum);
			paraMap.put("pageSize",pageSize);
			paraMap.put("endNum",endNum);
			
			responsePage.setPage(p.getPage());
			responsePage.setPageSize(pageSize);
			//3 根据实体对象获取映射的mapper，然后请求参数获取分页总记录数
			int count=pageCount(clazz, arrs, values);
			responsePage.setTotal(count);
		}
		
		//4 根据实体对象获取映射的mapper，然后请求参数获取分页信息
		List<T> data =crmSqlSession.selectList(statement, paraMap);
		//5 封装成功Page对象
		responsePage.setData(data);

		return responsePage;
	}

	private  <T extends Serializable>String getStatement(Class<T> clazz, String prefix) {
		//com.lazy.dao.UserMapper.pageCountUser

		 	String entityName = clazz.getSimpleName();  
		 	String entityName2 = clazz.getSimpleName();
		 	 if (entityName.endsWith("Mapper")) {  
		            entityName = entityName.substring(0, entityName.length() - 6);  
		        }  
	        String nameSpace=clazz.getPackage().getName()+"."+entityName2;
	        
	        return nameSpace + "." + prefix + entityName;  
	}

	private  <T extends Serializable> int pageCount(Class<T> clazz, String[] arrs, Object[] values) {
		Map<String, Object> paraMap = new HashMap<String, Object>(); 
		if(values!=null&&arrs!=null) {
			for(int i=0;i<values.length;i++) {
				paraMap.put(arrs[i], values[i]);
			}
		}
		 String statement = getStatement(clazz, "pageCount");  
	       Object o = crmSqlSession.selectOne(statement,paraMap);  
	       return Integer.parseInt(o.toString()); 
	}

}
